package com.joe.socket.Dao;

import com.joe.socket.Model.ChatMessage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Repository
public class MessageHistoryDao {

    private final List<ChatMessage> messageHistory = new CopyOnWriteArrayList<>();
    private static final int MAX_HISTORY_SIZE = 1000;

    public void saveMessage(ChatMessage message) {
        if (message != null) {
            messageHistory.add(message);

            // 限制历史消息数量
            if (messageHistory.size() > MAX_HISTORY_SIZE) {
                messageHistory.remove(0);
            }
        }
    }

    public List<ChatMessage> getRecentMessages(int count) {
        int startIndex = Math.max(0, messageHistory.size() - count);
        return new ArrayList<>(messageHistory.subList(startIndex, messageHistory.size()));
    }

    public List<ChatMessage> getMessagesByUser(String username) {
        return messageHistory.stream()
                .filter(msg -> username != null && username.equals(msg.getSender()))
                .collect(Collectors.toList());
    }

    public List<ChatMessage> getAllMessages() {
        return new ArrayList<>(messageHistory);
    }

    public void clearHistory() {
        messageHistory.clear();
    }

    public int getMessageCount() {
        return messageHistory.size();
    }

    /**
     * 获取系统消息
     */
    public List<ChatMessage> getSystemMessages() {
        return messageHistory.stream()
                .filter(msg -> msg.getType() == ChatMessage.MessageType.SYSTEM)
                .collect(Collectors.toList());
    }

    /**
     * 获取指定时间段的消息（时间戳范围）
     */
    public List<ChatMessage> getMessagesByTimeRange(long startTime, long endTime) {
        return messageHistory.stream()
                .filter(msg -> msg.getTimestamp() >= startTime && msg.getTimestamp() <= endTime)
                .collect(Collectors.toList());
    }
}